/**  
 * @Project: CmsADDT
 * @Title: HttpRequest.java
 * @Package fitnesse.fixture
 * @Description: HttpFixture解析FitNesse对应的Column表格
 * @author yanglei yanglei1@funshion.com
 * @date 2014年11月12日 上午10:55:01
 * @Copyright: 2014 funshion.com. All rights reserved.
 * @version V1.0  
 */
package util;

import java.util.HashMap;
import java.util.Map;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

/**
 * @ClassName HttpRequest
 * @Description HttpUtil
 * @author yanglei1 yanglei1@funshion.com
 * @date 2014年11月12日
 */
public class HttpUtil {

	private static final String SPLIT_CHAR = "&";
	
	public static final String POST_METHOD = "POST";
	public static final String GET_METHOD = "GET";

	public String description;
	public String method;
	public String url;
	public String fileds;
	public String headers;

	public Map<String, Object> paramsFormat(String params) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!params.equals("") || params != null) {
			String[] keyValues = params.split(SPLIT_CHAR);
			for (String each : keyValues) {
				map.put(each.substring(0, each.indexOf("=")),
						each.substring(each.indexOf("=") + 1));
			}
		}
		return map;
	}

	public String httpRequest(String method, String url, String fileds,
			Map<String, String> headers) throws Exception {
		String result = null;
		if (method.equals(POST_METHOD)) {
			result = postMethod(url, fileds, headers);
		} else if (method.equals(GET_METHOD)) {
			result = getMethod(url, null, headers);
		} else {
			throw new Exception("method is invalid, it's not support");
		}
		return result;
	}

	private String getMethod(String url, String fileds, Map<String, String> headers)
			throws UnirestException {
		HttpResponse<JsonNode> jsonResponse = Unirest.get(url).headers(headers)
				.asJson();
		return jsonResponse.getBody().toString();
	}

	private String postMethod(String url, String fileds,
			Map<String, String> headers) throws UnirestException {
		Map<String, Object> parasMap = paramsFormat(fileds);
		HttpResponse<JsonNode> jsonResponse = Unirest.post(url)
				.headers(headers).fields(parasMap).asJson();
		return jsonResponse.getBody().toString();
	}
}